﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using ESRI.ArcGIS.ArcMapUI;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;

namespace ODM_Code.Code
{
    public class SetDecisionVariablesCode
    {
        //private IMxDocument doc;
        private Dictionary<string, int> _43Dict;

        public SetDecisionVariablesCode(IMxDocument doc)
        {
            //this.doc = doc;
            _43Dict = new Dictionary<string, int>();
        }

        public int[] GetPeriods(string inputPath)
        {
            string provider = "Provider=VFPOLEDB.1";
            string dataSrc = "data source=" + inputPath + "\\_31.DBF";
            string conStr = provider + ";" + dataSrc + ";";
            string select = "SELECT * FROM _31";

            try
            {
                OleDbConnection cnxn = new OleDbConnection(conStr);
                DataSet ds = new DataSet();
                OleDbCommand cmd = new OleDbCommand(select, cnxn);
                OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);

                adapter.Fill(ds);
                DataTable dt = ds.Tables["Table"];
                DataRow row = dt.Rows[0];

                object val = row["Time_perds"];
                int iVal = Convert.ToInt16(val);

                int[] periods = new int[iVal];
                for (int i = 1; i <= iVal; i++)
                {
                    periods[i - 1] = i;
                }

                cnxn.Close();

                return periods;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.Message, "GetPeriods");
                return null;
            }

        }

        public string GetTreatFilePath(string inputPath)
        {
            string treatfile = inputPath + "\\treat.shp";
            if (File.Exists(treatfile))
            {
                return treatfile;
            }
            else
            {
                System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
                ofd.InitialDirectory = inputPath;
                ofd.Title = "Select a treatment shapefile";
                ofd.Filter = "Shapefiles (*.shp)|*.shp";
                ofd.ShowDialog();
                return ofd.FileName;
            }
        }

        public List<string> GetTreatments(string inputPath)
        {
            string provider = "Provider=VFPOLEDB.1";
            string dataSrc = "data source=" + inputPath + "\\_43b.DBF";
            string conStr = provider + ";" + dataSrc + ";";
            string select = "SELECT * FROM _43b";

            try
            {
                OleDbConnection cnxn = new OleDbConnection(conStr);
                DataSet ds = new DataSet();
                OleDbCommand cmd = new OleDbCommand(select, cnxn);
                OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);

                adapter.Fill(ds);
                DataTable dt = ds.Tables["Table"];
                DataRowCollection rows = dt.Rows;

                List<string> treatments = new List<string>();

                foreach (DataRow dr in rows)
                {
                    object val = dr["Name"];
                    string sVal = Convert.ToString(val);
                    
                    object id = dr["In_mgrg_id"];
                    int iId = Convert.ToInt16(id);

                    treatments.Add(sVal);
                    _43Dict[sVal] = iId;
                }

                cnxn.Close();

                return treatments;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.Message, "GetTreatments");
                return null;
            }
        }

        public List<int> IntPrjIdLookup(string inputPath, List<int> cuttingUnits, string action, int period)
        {
            List<int> intprjids = new List<int>();

            string provider = "Provider=VFPOLEDB.1";
            string dataSrc = "data source=" + inputPath + "\\_54.DBF";
            string conStr = provider + ";" + dataSrc + ";";
            string select = "SELECT * FROM _54";

            try
            {
                OleDbConnection cnxn = new OleDbConnection(conStr);
                DataSet ds = new DataSet();
                OleDbCommand cmd = new OleDbCommand(select, cnxn);
                OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);

                adapter.Fill(ds);
                DataTable dt = ds.Tables["Table"];

                foreach (int cu in cuttingUnits)
                {
                    string expr = 
                        "Comp1 = " + cu.ToString() + " AND " + 
                        "Comp2 = " + _43Dict[action].ToString() + " AND " + 
                        "Comp5 = " + period.ToString();

                    DataRow[] drs = dt.Select(expr);

                    if (drs.Length > 0)
                    {
                        DataRow dr = (DataRow)drs.GetValue(0);
                        if (dr.ItemArray.Length > 0)
                        {
                            object val = dr[0];
                            int iVal = Convert.ToInt16(val);
                            intprjids.Add(iVal);
                        }
                    }
                }

                cnxn.Close();

                return intprjids;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.Message, "GetPeriods");
                return intprjids;
            }
        }

        public List<int> LookupFeatures(IFeatureLayer treatFeat, bool onlySelected)
        {
            List<int> selectedCuttingUnits = new List<int>();
            IFeatureSelection featSelect = (IFeatureSelection)treatFeat;

            if (featSelect.SelectionSet.Count > 0)
            {
                ICursor cCursor;
                featSelect.SelectionSet.Search(null, true, out cCursor);
                IFeatureCursor fCursor = (IFeatureCursor)cCursor;
                int numericCuttingUnit = fCursor.FindField("NCUT_UN_ID");

                IFeature f;

                for (int i = 0; i < featSelect.SelectionSet.Count; i++)
                {
                    f = fCursor.NextFeature();
                    object val = f.get_Value(numericCuttingUnit);
                    int iVal = Convert.ToInt16(val);
                    selectedCuttingUnits.Add(iVal);
                }
            }

            return selectedCuttingUnits;
        }

        public void WriteDVFile(string pathToDVFile, List<int> newDVs)
        {
            if (File.Exists(pathToDVFile))
            {
                StreamReader sr = new StreamReader(pathToDVFile);
                sr.ReadLine();

                string line;
                string[] spl;
                int dv;

                while (!sr.EndOfStream)
                {
                    line = sr.ReadLine();
                    spl = line.Split('\t');
                    dv = int.Parse(spl[0]);
                    newDVs.Add(dv);
                }

                sr.Close();
            }

            newDVs.Sort();
            
            StreamWriter sw = new StreamWriter(pathToDVFile);
            sw.WriteLine("int_prj_id\tstatus");

            foreach (int i in newDVs)
            {
                sw.WriteLine(i.ToString() + "\t1");
            }

            sw.Close();
        }
    }
}
